package cn.git.agent.boot;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;

/**
 * @description: 获取agent-jar对应目录信息
 * @program: bank-credit-sy
 * @author: lixuchun
 * @create: 2024-12-26
 */
public class AgentPackagePath {

    /**
     * agent-jar所在目录file对象
     */
    private static File AGENT_PACKAGE_PATH;

    public static File getPath() {
        if (AGENT_PACKAGE_PATH == null) {
            AGENT_PACKAGE_PATH = findPath();
        }
        return AGENT_PACKAGE_PATH;
    }

    public static boolean isPathFound() {
        return AGENT_PACKAGE_PATH != null;
    }

    /**
     * 获取agent-jar所在目录
     *
     * @return agent-jar所在目录
     */
    private static File findPath() {
        // 结果 cn/git/agent/boot/AgentPackagePath.class
        String classResourcePath = AgentPackagePath.class.getName().replaceAll("\\.", "/") + ".class";

        // 获取到agent-jar的url，D:\idea_workspace\bytebuddy-demo\git-agent-demo\apm-sniffer\amp-agent\target\amp-agent-1.0-SNAPSHOT-jar-with-dependencies.jar
        URL resource = ClassLoader.getSystemClassLoader().getResource(classResourcePath);
        if (resource != null) {
            String urlString = resource.toString();

            System.out.println("The beacon class location is " + urlString + ".");

            // 判断agent-jar是否在jar中，在jar包中路径包含 !
            int insidePathIndex = urlString.indexOf('!');
            boolean isInJar = insidePathIndex > -1;

            if (isInJar) {
                urlString = urlString.substring(urlString.indexOf("file:"), insidePathIndex);
                File agentJarFile = null;
                try {
                    agentJarFile = new File(new URL(urlString).toURI());
                } catch (MalformedURLException | URISyntaxException e) {
                    System.out.println("Can not locate agent jar file by url:" + urlString);
                }
                if (agentJarFile.exists()) {
                    return agentJarFile.getParentFile();
                }
            } else {
                int prefixLength = "file:".length();
                String classLocation = urlString.substring(
                        prefixLength, urlString.length() - classResourcePath.length());
                return new File(classLocation);
            }
        }

        System.out.println("Can not locate agent jar file.");
        throw new RuntimeException("Can not locate agent jar file.");
    }

}
